<script>
export default {
  name:"product",
  data() {
    let checkBarCode =(rule,value,callback)=>{
      if(this.form.id){
        return callback();
      }
      this.$axios.post("/zzh-product-price/findeByBarCode?BarCode="+this.form.barCode).then(res=>res.data).then(res=>{
        if(res.resultCode!=200){
          callback()
        }else{
          callback(new Error('单据编号已经存在'));
        }
      })
    };
    return {
      tableData: [],
      activeName: 'first',
      imageUrl: '',
      photoBase64: '',
      thumbnailUrl: null,
      selectedFile: null,
      hashMapProductUnits:{},
      hashMapProductAttributes:{},
      hashMapDepots:{},
      listProductCategories:[],
      zzhProductStockList:[],
      pageNum:1,
      pageSize:5,
      total:5,
      name:'',
      TreeData:[],
      selectedNode:[],
      selectedId: "",
      selectedValue: null,
      selectedDepotId:"",
      defaultProps: {
        valueL:'id',
        children: 'children',
        label: 'label'
      },
      dialogVisible:false,
      loading: true,
      form:{
        id:'',
        categoryId:'',
        name:'',
        mfrs:'',
        model:'',
        standard:'',
        color:'',
        unitId:'',
        remark:'',
        imgName:'',
        expiryNum:'',
        weight:'',
        position:'',
        status:'',
        barCode:'',
        commodityUnit:'',
        sku:'',
        purchaseDecimal:'',
        wholesaleDecimal:'',
        lowDecimal:'',
        defaultFlag:'',
        depotId:'',
        currentNumber:'',
        lowNumber:'',
        highNumber:'',
        zzhProductStocks:[],
      },
      rules: {
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { min: 3, max: 18, message: '长度在 3 到 18 个字符', trigger: 'blur' },
        ],
        unitId: [
          { required: true, message: '输入单位', trigger: 'blur' }
        ],
        barCode:[
          { required: true, message: '请输入条码', trigger: 'blur' },
          { min: 3, max: 18, message: '长度在 3 到 18 个字符', trigger: 'blur' },
          {validator:checkBarCode,trigger: 'blur'}
        ]
      }
    };
  },
  methods:{
    //查询商品属性|计量单位|库存|类别信息
    loadOption(){
      this.$axios.get('/zzh-product/option').then(res=>res.data).then(res=>{
        if(res.resultCode==200){
          this.hashMapProductUnits = res.data.hashMapProductUnits;
          this.hashMapProductAttributes = res.data.hashMapProductAttributes;
          this.listProductCategories = res.data.listProductCategories;
          this.hashMapDepots = res.data.hashMapDepots;
          this.form.zzhProductStocks = res.data.ZzhProductStocks;
          this.zzhProductStockList=res.data.ZzhProductStocks;
          console.log(this.hashMapProductAttributes)
          console.log(this.hashMapProductUnits)
        }else {
          alert('获取数据失败')
        }
      })
    },
    //查询所有商品详情分页
    loadPost(){
      this.loading = true;
      this.$axios.post('/zzh-product/list',{
        page:this.pageNum,
        limit:this.pageSize,
        name:this.name,
        categoryId:this.form.categoryId
      }).then(res=>res.data).then(res=>{
          this.loading = false;
        if(res.resultCode==200){
          this.tableData=res.data
          this.total=res.total
          console.log(this.tableData)
        }else {
          alert('获取数据失败')
        }
      })
    },
    //点击添加按钮，弹出添加对话框
    add(){
      this.dialogVisible=true
      this.$nextTick(()=>{
        this.resetForm()
      })
    },
    //判断点击了修改按钮还是添加按钮
    loadAdd(){
      //表单验证
      this.$refs.form.validate((valid) => {
        if (valid) {
          if(this.form.id){
            this.doUpdate();
          }else {
            this.doAdd()
          }
        } else {
          return false;
        }
      });
    },
    //进行添加操作
    doAdd(){
      this.$axios.post('/zzh-product/add',this.form).then(res=>res.data).then(res=>{
        this.resetForm();
        if(res.resultCode==200){
          this.dialogVisible=false
          this.$message({
            showClose: true,
            message: '新增数据成功',
            type: 'success'
          });
          this.loadPost()
        }else {
          this.$message({
            showClose: true,
            message: '新增数据失败',
            type: 'error'
          });
        }
      })
    },
    //进行更新前赋值操作
    mod(row){
      this.dialogVisible=true
      this.$nextTick(()=>{
        this.form.id=row.id
        this.form.categoryId=row.categoryId
        this.form.name=row.name
        this.form.mfrs=row.mfrs
        this.form.model=row.model
        this.form.standard=row.standard
        this.form.color=row.color
        this.form.unitId=row.unitId
        this.form.remark=row.remark
        for (let key in this.hashMapProductUnits) {
          if (parseInt(key) === this.form.unitId) {
            this.form.unitId = this.hashMapProductUnits[key]; // 将 key 设置为选中值
            break;
          }
        }
        this.$axios.post('/zzh-tool/getPhoto?imgName='+row.imgName)
            .then(response => {
              this.photoBase64 = response.data;
            })
            .catch(error => {
              console.error(error);
            });
        this.form.expiryNum=row.expiryNum
        this.form.weight=row.weight
        this.form.position=row.position
        this.form.barCode=row.barCode
        this.form.commodityUnit=row.commodityUnit
        this.form.sku=row.sku
        console.log(this.form.unitId)
        console.log(this.form.sku)
        this.form.purchaseDecimal=row.purchaseDecimal
        this.form.wholesaleDecimal=row.wholesaleDecimal
        this.form.lowDecimal=row.lowDecimal
        this.form.depotId=row.depotId
        this.form.currentNumber=row.currentNumber
        this.form.lowNumber=row.lowNumber
        this.form.highNumber=row.highNumber
        this.form.zzhProductStocks=row.zzhProductStocks
        for (let key in this.hashMapDepots) {
          if (parseInt(key) === this.form.depotId) {
            this.selectedDepotId = this.hashMapDepots[key]; // 将 key 设置为选中值
            break;
          }
        }
      })
      if(this.form.categoryId) {
        this.$axios.post("/zzh-product-category/findeById?id=" + this.form.categoryId).then(res => res.data).then(res => {
          this.selectedValue = res.data.name
        })
      }
    },
    //进行更新操作
    doUpdate(){
      this.$axios.put('/zzh-product/update',this.form).then(res=>res.data).then(res=>{
        this.resetForm();
        if(res.resultCode==200){
          this.dialogVisible=false
          this.$message({
            showClose: true,
            message: '更新数据成功',
            type: 'success'
          });
          this.form.categoryId=''
          this.form.imgName=''
          this.imageUrl=''
          this.loadPost()
        }else {
          this.$message({
            showClose: true,
            message: res.message,
            type: 'error'
          });
        }
      })
    },
    //进行删除操作
    del(id){
      this.$axios.delete('/zzh-product/delete?id='+id).then(res=>res.data).then(res=>{
        if(res.resultCode==200){
          this.$message({
            showClose: true,
            message: '删除成功',
            type: 'success'
          });
          this.loadPost()
        }else {
          this.$message({
            showClose: true,
            message: '删除失败',
            type: 'error'
          });
        }
      })
    },
    //进行更新角色状态
    updateStatus(id){
      this.$axios.put('/zzh-product/updateStatus?id='+id).then(res=>res.data).then(res=>{
        if(res.resultCode==200){
          this.$message({
            showClose: true,
            message: '更新状态成功',
            type: 'success'
          });
          this.loadPost()
        }else {
          this.$message({
            showClose: true,
            message: '更新状态失败',
            type: 'error'
          });
        }
      })
    },
    //树节点数据赋值
    handleAddClick(data){
      this.selectedNode = [data]; // 将选中的节点数据赋值给selectedNode
      this.selectedValue = data.label; // 将选中的节点值赋值给selectedValue
      this.form.categoryId=data.id
    },
    //进行分页操作
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageNum=1
      this.pageSize=val
      this.loadPost()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.pageNum=val
      this.loadPost()
    },
    //重新刷新
    resetParam(){
      this.name=''
      this.selectedValue=''
      this.form.categoryId=''
      this.loadPost()
    },
    //导出数据
    exportExcel() {
      //将响应数据类型设置为 Blob 对象   原因: 确保文件等二进制数据在传输过程中不会被转换或解析,对于文件下载非常有用，因为你可以直接将返回的二进制数据用于创建可下载的文件
      this.$axios.post('/zzh-excel/produceExcel',this.tableData, { responseType: 'blob' })
          .then(response => {
            // 将获取到的Excel数据转换为文件
            //Blob是二进制的容器，可以存放任意类型的二进制文件：图片/音频/文件
            //type : 类型设为Excel文件（.xlsx）的MIME类型，告诉浏览器创建的是一个Excel文件，默认使用excel打开
            const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });

            // 创建隐藏的下载链接并模拟点击下载
            const link = document.createElement('a');
            //创建一个可供用户下载的链接
            link.href = URL.createObjectURL(blob);
            link.download = '商品信息表格.xlsx';
            //设置链接的打开方式为新标签页（_blank），这样用户点击链接后会在新标签页中下载文件
            link.target = '_blank';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
          })
          .catch(error => {
            console.error(error);
          });
    },
    //重置窗体表单
    resetForm() {
      this.form.id='';
      this.form.name="";
      this.form.standard="";
      this.form.model="";
      this.form.unitId="";
      this.form.color="";
      this.form.weight="";
      this.form.expiryNum="";
      this.form.mfrs="";
      this.form.position="";
      this.form.sku="";
      this.form.remark="";
      this.form.barCode="";
      this.form.commodityUnit="";
      this.form.purchaseDecimal="";
      this.form.wholesaleDecimal="";
      this.form.lowDecimal="";
      this.form.currentNumber="";
      this.form.lowNumber="";
      this.form.highNumber="";
      this.form.zzhProductStocks=this.zzhProductStockList;
      this.selectedValue="";
      this.selectedDepotId="";
      //通过this.$refs.form可以访问名为"form"的子组件或DOM元素
      //调用resetFields()方法将重置表单元素的值和校验状态，使表单恢复到最初的空白状态
      this.$refs.form.resetFields();
    },
    //数据筛选
    handleSelectChangeDepotId(){
      this.form.depotId = this.selectedDepotId;
      for (let key in this.hashMapDepots) {
        if (parseInt(key) === this.form.depotId) {
          this.selectedDepotId = this.hashMapDepots[key]; // 将 key 设置为选中值
          break;
        }
      }
    },
    //判断是否为空，为空就赋值空值
    getDepartmentName(id){
      return this.hashMapProductCategory[id] || '';
    },
    // tap事件
    handleClick(tab, event) {
      console.log(tab, event);
    },
    //上传图片事件
    selectFile() {
      this.$refs.fileInput.click(); // 触发文件选择
    },
    //反显照片
    handleFileChange(event) {
      this.selectedFile = event.target.files[0];
      this.thumbnailUrl = URL.createObjectURL(this.selectedFile);
    },
    //上传照片
    uploadFile() {
      if (this.selectedFile) {
        const formData = new FormData();
        formData.append('file', this.selectedFile);
        this.$axios
            .post('/zzh-tool/upload', formData, {
              headers: {
                'Content-Type': 'multipart/form-data', // 必须设置合适的 Content-Type
              },
            })
            .then(res => res.data)
            .then(res => {
              this.form.imgName=res.data.fileName
              this.$axios.post('/zzh-tool/getPhoto?imgName='+this.form.imgName)
                  .then(response => {
                    this.photoBase64 = response.data;
                  })
                  .catch(error => {
                    console.error(error);
                  });
              this.$message({
                showClose: true,
                message: '上传成功',
                type: 'success'
              });
            })
            .catch(error => {
              this.$message({
                showClose: true,
                message: '上传失败',
                type: 'error'
              });
            });
      }
    },
  },
  beforeMount() {
    this.loadOption();
    this.loadPost();
  }

}
</script>

<template>
  <div>
    <!--    按钮-->
    <div style="margin-bottom: 5px">
      <el-select v-model="selectedValue" filterable placeholder="请选择属性" style="margin-left: 5px">
        <el-option
            v-for="item in listProductCategories" :key="item.id" :value="item.label" :label="item.label"
            v-show="false"></el-option>
        <el-tree
            v-model="selectedNode"
            :data="listProductCategories"
            :props="defaultProps"
            default-expand-all
            @node-click="handleAddClick"
        ></el-tree>
      </el-select>
      <el-input v-model="name" placeholder="请输入条码等关键词" suffix-icon="el-icon-search" style="width: 200px;margin-left: 5px"
                @keyup.enter.native="loadPost"></el-input>

      <el-button type="primary" style="margin-left: 5px" @click="loadPost">查询</el-button>
      <el-button type="success" @click="resetParam">重置</el-button>
      <el-button type="primary" style="margin-left: 5px" @click="add">新增</el-button>
      <el-button type="success" plain @click="exportExcel" style="margin-left: 10px" icon="el-icon-download">导出Excel</el-button>
    </div>
    <!--    表单-->
    <el-table :data="tableData" v-loading="loading"
              :header-cell-style="{background:'#f3f6fd',color:'#555'}">
      <el-table-column prop="operate" label="操作" width="240">
        <template slot-scope="scope">
          <el-button size="small" type="success" @click="mod(scope.row)">编辑</el-button>
          <el-popconfirm
              title="确定删除吗？"
              style="margin-left: 5px;margin-right: 5px"
              @confirm="del(scope.row.id)"
          >
            <el-button slot="reference" size="small" type="danger">删除</el-button>
          </el-popconfirm>
          <el-button size="small" type="success" @click="updateStatus(scope.row.id)">启用/禁用</el-button>

        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="120">
        <template slot-scope="scope">
          <el-tag
              :type="scope.row.status === 1 ? 'success' : 'danger'"
              disable-transitions>{{scope.row.status === 1 ? '正常' : scope.row.status === 2 ? '禁用' : '已删除'}}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="barCode" label="条码" width="140">
      </el-table-column>
      <el-table-column prop="name" label="名称" width="140">
      </el-table-column>
      <el-table-column prop="standard" label="规格" width="120">
      </el-table-column>
      <el-table-column prop="model" label="型号" width="120">
      </el-table-column>
      <el-table-column prop="color" label="颜色" width="120">
      </el-table-column>
      <el-table-column prop="categoryId" label="类别" width="120">
      </el-table-column>
      <el-table-column prop="currentNumber" label="库存" width="120">
      </el-table-column>
      <el-table-column prop="purchaseDecimal" label="采购价" width="120">
      </el-table-column>
      <el-table-column prop="wholesaleDecimal" label="销售价" width="120">
      </el-table-column>
      <el-table-column prop="lowDecimal" label="最低售价" width="120">
      </el-table-column>
    </el-table>

    <!--    分页-->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNum"
        :page-sizes="[2, 5, 10, 20]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
    </el-pagination>

    <!--    提示框-->
    <el-dialog
        title="提示"
        :visible.sync="dialogVisible"
        width="70%"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" size="mini" v-loading="loading">
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="基本信息" name="first">
            <el-row>
              <el-col :span="6">
                <el-form-item label="名称：" prop="name">
                  <el-input v-model="form.name" placeholder="请输入名称"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="规格：">
                  <el-input v-model="form.standard" placeholder="请输入规格"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="型号：">
                  <el-input v-model="form.model" placeholder="请输入型号"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="多单位：">
                  <el-select v-model="form.unitId" filterable placeholder="请选择多单位" style="margin-left: 5px">
                    <el-option
                        v-for="(key,value) in hashMapProductUnits"
                        :key="value"
                        :label="key"
                        :value="value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="6">
                <el-form-item label="颜色：">
                  <el-input v-model="form.color" placeholder="请输入颜色"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="基础重量：">
                  <el-input v-model="form.weight" placeholder="请输入基础重量(kg)"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="保质期：">
                  <el-input v-model="form.expiryNum" placeholder="请输入保质期天数"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="类别：" prop="parentId">
                  <el-select v-model="selectedValue" filterable placeholder="请选择类别" style="margin-left: 5px">
                    <el-option
                        v-for="item in listProductCategories" :key="item.id" :value="item.label" :label="item.label"
                        v-show="false"></el-option>
                    <el-tree
                        v-model="selectedNode"
                        :data="listProductCategories"
                        :props="defaultProps"
                        default-expand-all
                        @node-click="handleAddClick"
                    ></el-tree>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="6">
                <el-form-item label="供应商：">
                  <el-input v-model="form.mfrs" placeholder="请输入供应商名称"></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="货架：">
                  <el-input v-model="form.position" placeholder="请输入货架"></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="多属性：">
                  <el-select v-model="form.sku" filterable placeholder="请选择多属性" style="margin-left: 5px">
                    <el-option
                        v-for="(key,value) in hashMapProductAttributes"
                        :key="value"
                        :label="key"
                        :value="value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>


            <el-form-item label="备注：">
              <el-input v-model="form.remark" placeholder="请输入备注"></el-input>
            </el-form-item>
          </el-tab-pane>

          <el-tab-pane label="商品价格" name="second">
            <el-form-item label="商品条码" prop="barCode">
              <el-input v-model="form.barCode"  placeholder="请输入商品条码"></el-input>
            </el-form-item>
            <el-form-item label="商品单位">
              <el-input v-model="form.commodityUnit"  placeholder="请输入商品单位"></el-input>
            </el-form-item>
            <el-form-item label="采购价格">
              <el-input v-model="form.purchaseDecimal" type="number"  placeholder="请输入采购价格"></el-input>
            </el-form-item>
            <el-form-item label="销售价格">
              <el-input v-model="form.wholesaleDecimal" type="number"  placeholder="请输入销售价格"></el-input>
            </el-form-item>
            <el-form-item label="最低售价">
              <el-input v-model="form.lowDecimal" type="number"  placeholder="请输入最低售价"></el-input>
            </el-form-item>
          </el-tab-pane>

          <el-tab-pane label="库存数量" name="third">
            <el-table :data="form.zzhProductStocks" ref="table" size="small">
              <el-table-column prop="depotId" label="仓库名称">
                <template slot-scope="scope">
                  <!-- 在这里进行遍历和查询 -->
                  <span v-for="value in hashMapDepots[scope.row.depotId]">
                    {{ value }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column prop="currentNumber" label="当前库存数量">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.currentNumber" type="number" placeholder="请输入数量"></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="lowNumber" label="最低库存数量">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.lowNumber" type="number" placeholder="请输入数量"></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="highNumber" label="最高库存数量">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.highNumber" type="number" placeholder="请输入数量"></el-input>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>

          <el-tab-pane label="图片信息" name="fourth">
            <input type="file" ref="fileInput" style="display: none" @change="handleFileChange" />
            <el-button @click="selectFile" type="primary">选择文件</el-button>
            <el-button @click="uploadFile" type="success">上传</el-button>

            <div>
              <img v-if="thumbnailUrl" :src="thumbnailUrl" alt="Thumbnail" style="max-width: 200px; max-height: 200px; display: none" />
              <img :src="'data:image/jpeg;base64,' + photoBase64" alt="照片" style="max-width: 200px; max-height: 200px;" >
            </div>
          </el-tab-pane>
        </el-tabs>

      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="loadAdd">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<style scoped>

.avatar-uploader .el-upload {
  border: 1px dashed #635f5f;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>